import React, { Component } from "react";
import Modal from 'bee-modal';
import 'bee-modal/build/Modal.css';
import Table from "bee-table";
import { Button, Checkbox, Radio, Icon, InputGroup, FormControl, Tree } from "tinper-bee";
// import Tree from 'bee-tree';
const TreeNode = Tree.TreeNode;
// import 'bee-tree/build/Tree.css';
import selfNaxios from 'utils/ajaxConfig.js';
import { vendorsDanger } from 'utils/config.js';
import './index.less'
let searchTimer;

class TreeRefer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            keyword: '',
        }
        this.dataMap = new Map();
    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        let {
            isShow,
            refPk,
            refUrl,
            refMethod = 'get',
            refQueryCondition,
            resultPath,
            selected = [],
            isMultiSelectedEnabled,
        } = this.props;
        if (prevProps.isShow && !isShow) {
            this.setState({
                expandedKeys: [],
                autoExpandParent: true,
                checkedKeys: [],
                selectedKeys: [],
                keyword: '',
                treeData: [],
            });
        }
        if (!prevProps.isShow && isShow) {
            let paramKey = refMethod == 'get' ? 'params' : 'data';
            if (!isMultiSelectedEnabled) {
                selected = selected ? [selected] : [];
            } else {
                selected = selected || [];
            }
            selfNaxios({
                method: refMethod,
                url: refUrl,
                [paramKey]: typeof refQueryCondition === 'function' ? refQueryCondition.call(this) : null,
            }, (res) => {
                let resData = res.data;
                if (resData.resultCode === 'ok') {
                    let data = resData.result;
                    if (resultPath) {
                        data = data[resultPath];
                    }
                    data = Array.isArray(data) ? data : [data];
                    this.dataMap = new Map();
                    this.dealReceiveData(data);
                    this.setState({
                        treeData: data,
                        checkedKeys: selected,
                        selectedKeys: selected,
                    });
                } else {
                    vendorsDanger({ text: resData.exMsg }); //Todo
                }
            }, (error) => {
                console.error(error);
            })
        }
    }

    dealReceiveData = (data) => {
        let {
            nameField,
            codeField,
            valueField,
            childernName = 'children',
        } = this.props;
        data.forEach(cur => {
            cur.title = cur[nameField];
            cur.key = cur[valueField];
            this.dataMap.set(cur.key, cur);
            if (cur[childernName]) {
                this.dealReceiveData(cur[childernName]);
            }
        })
    }

    onExpand = expandedKeys => {
        console.log('onExpand', expandedKeys);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };

    onCheck = checkedKeys => {
        console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    };

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        if (!this.props.onlyLeaf) {
            this.setState({ selectedKeys });
        } else {
            if (selectedKeys.length !== 0 && info.node.props.children) {
                this.setState({ selectedKeys: [] });
            } else {
                this.setState({ selectedKeys });
            }
        }
    };
    onDoubleClick = (checkedKeys, e) => {
        if (!this.props.isMultiSelectedEnabled) {
            this.sureClick();
        }
    }

    onTextSearch = (e) => {
        clearTimeout(searchTimer)
        let keyword = e.target.value;
        searchTimer = setTimeout(() => {
            this.setState({
                keyword,
            })
        }, 300);
    }
    sureClick = () => {
        let { refPk, fieldDisplayed, fieldValued, isMultiSelectedEnabled } = this.props;
        let display = [], value = [];

        if (isMultiSelectedEnabled) {
            this.state.checkedKeys.forEach(cur => {
                display.push(this.dataMap.get(cur)[this.props.nameField]);
            })
            this.setState({
                checkedKeys: [],
            })
            display = display.join(',');
            value = this.state.checkedKeys;
        } else {
            if (this.state.selectedKeys.length > 0
                && this.state.selectedKeys[0]
                && this.state.selectedKeys[0] != 'null') {
                value = this.state.selectedKeys[0];
                display = this.dataMap.get(this.state.selectedKeys[0])[this.props.nameField];
            } else {
                display = '';
                value = '';
            }
            this.setState({
                selectedKeys: [],
            })
        }

        this.props.getSelected(this.props.attrcode, { display, value });
        this.props.closeRefer();
    }
    loop = data => {
        if (!data) return null;
        let { childernName = 'children' } = this.props;
        return data.map((item) => {
            if (item[childernName]) {
                return <TreeNode
                    // icon={this.renderTreeNodeIcon(item[childernName])}
                    key={item.key}
                    title={item.title}>{this.loop(item[childernName])}</TreeNode>;
            }
            return <TreeNode
                // icon={this.renderTreeNodeIcon(item[childernName])}
                key={item.key} title={item.title} />;
        })
    }
    // keydown的钩子事件
    onKeyDown = (e, treeNode) => {
        console.log('***', e);
        return false;
    }
    render() {
        let {
            isMultiSelectedEnabled,
            isShow = false,
            closeRefer,
            label,
            refPk,
            filterColumn,
        } = this.props;
        // let tableData = this.state.data
        // if (filterColumn && this.state.keyword)
        //     tableData = tableData.filter(cur => {
        //         return cur[filterColumn] && cur[filterColumn].includes(this.state.keyword);
        //     })
        return (
            <div>
                <Modal className='ygc-tree-refer' show={isShow} size={'lg'} onHide={closeRefer} backdrop={false}>
                    <Modal.Header closeButton>
                        <Modal.Title > {label} </Modal.Title>
                    </Modal.Header >
                    <Modal.Body>
                        {filterColumn &&
                            <InputGroup simple className='u-search-group'>
                                <FormControl
                                    type="text"
                                    onChange={this.onTextSearch}
                                />
                                <InputGroup.Button shape="border">
                                    <span className="uf uf-search"> </span>
                                </InputGroup.Button>
                                {/* <InputGroup.Button>
                                <Button><span className="uf uf-search"> </span></Button>
                            </InputGroup.Button> */}
                            </InputGroup>
                        }
                        <div style={{ height: '400px', overflow: 'auto' }}>
                            <Tree
                                checkable={isMultiSelectedEnabled}
                                // treeData={this.state.treeData}
                                lazyLoad={true}
                                onExpand={this.onExpand}
                                expandedKeys={this.state.expandedKeys}
                                autoExpandParent={true}
                                onCheck={this.onCheck}
                                checkedKeys={this.state.checkedKeys}
                                onSelect={this.onSelect}
                                selectedKeys={this.state.selectedKeys}
                                keyFun={this.onKeyDown}
                                renderTreeNodes={this.renderTreeNodes}
                                // onDoubleClick={this.onDoubleClick}
                            >
                                {this.loop(this.state.treeData)}
                            </Tree>
                        </div>
                    </Modal.Body>
                    <Modal.Footer>
                        <div className="refer-btn-group">
                            <Button className='icon-cancel-btn' onClick={closeRefer}> 取消 </Button>
                            <Button colors="primary" onClick={this.sureClick}> 确认 </Button>
                        </div>
                    </Modal.Footer>
                </Modal>
            </div>
        )
    }
}


export default TreeRefer;